#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

#include "sound.h"

void* soundThread(void* parent) {
	((Sound*)parent)->loop();
	pthread_exit(NULL);
	return NULL;
}

Sound::Sound(Sync* sync) {
	this->sync = sync;
	sem_init(&startSemaphore, 0, 1);

	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
	pthread_create(&thread, &attr, soundThread, (void *)this);
	pthread_attr_destroy(&attr);
}

Sound::~Sound() {
}

void
Sound::initialize() {
	// TODO: pre calc
}

void
Sound::start() {
	shutdown = false;
	sem_post(&startSemaphore); // signal start to the sound thread
}

void
Sound::stop() {
	void *status;
	shutdown = true;
	pthread_join(thread, &status);
}

void
Sound::loop() {
	sem_wait(&startSemaphore); // wait for the start signal

	sync->timeStart();
	while (!shutdown) {
		// TODO: play music
		usleep(500000);
	}
}
